import sys
import os
sys.path.insert(0, sys.path[0]+"/")
import time
from rich import print
from rich.console import Console
from rich.panel import Panel
from rich.text import Text
from rich.table import Table

import math
from .dataServices.fileEntity import fileEntity


class file:
    folder_list = []
    fileNumber = 0    

    totalPage = 0
    nowPage = 1
    def getFileList(self,path=f"{sys.path[0]+'/'}【input】inputDatabase"):
        index = 1
        for item in os.listdir(path):
            fileObject = {}
            fileObject['fileName'] = f"【{index}】 {item}"
            fileObject['fileSize'] = os.path.getsize(f"{sys.path[0]+'/'}【input】inputDatabase/{item}")/1000
            timeArray = time.localtime(os.path.getatime(f"{sys.path[0]+'/'}【input】inputDatabase/{item}"))
            otherStyleTime = time.strftime("%Y-%m-%d %H:%M:%S", timeArray)
            fileObject['fileCreateTime'] = otherStyleTime
            fileObject['fileUrl'] = f"{sys.path[0]+'/'}【input】inputDatabase/{item}"
            self.folder_list.append(fileObject)
   
            index+=1

        # file number
        self.fileNumber = index
        self.totalPage = math.ceil(index/10)
        self.nowPage = 1

        self.__showFileList()
        return self.folder_list

    def __showFileList(self,status=1):
        print(self.nowPage*10-10,self.nowPage*10)
        needShowArray = self.folder_list[self.nowPage*10-10:self.nowPage*10]
        self.__clear()
        table = Table(title=f"文件列表 【当前页 {self.nowPage}/{self.totalPage}】",header_style="bold magenta",expand=True,caption_justify="center")
        table.add_column("文件名", justify="left", style="cyan", no_wrap=True)
        table.add_column("大小", justify="left",style="magenta")
        table.add_column("时间", justify="left", style="green")

        for line in needShowArray:
            table.add_row(str(line['fileName']), f"{str(line['fileSize'])} KB",str(line['fileCreateTime']))
        console = Console()
        console.print(table)

        if status == -1: console.print("错误的命令！\n",style="bold red")
        self.__showFunctionListTips()

    def __switchPage(self,page):
        self.nowPage = page
        self.__showFileList()
        pass

    def __clear(self):
        os.system('cls')
        os.system('clear')

    def __showFunctionListTips(self):
        console = Console()
        console.print("【A】搜索 【page 页码】跳转页面 【W 序号】读取文件 【BACK】返回主菜单")
        console.print("$命令：",end="")
        instruct = input()
        if instruct == 'A' or instruct == 'a':
            pass
        elif  'page' in instruct or 'PAGE' in instruct:
            try:
                instructArray = instruct.split(' ')
                self.__switchPage(int(instructArray[1]))
            except ValueError:
                self.__showFileList(-1)
        elif instruct[0:1] == 'W' or instruct[0:1] == 'w':
            instructArray =  instruct.split(' ')
            fileEntity(self.folder_list[int(instructArray[1])-1]['fileUrl'])
            pass
        elif instruct == 'BACK' or instruct == 'back':
            from .userInterface import mainUI
            mainUI()
        else:
            self.__showFileList(-1)